/***************************************************************************
 *   Copyright (C) 2008 by Philipp Müller                                  *
 *   philipp.mueller@gmx.de                                                *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA          *
 ***************************************************************************/

#include <QtNetwork>

#include "vdrfindserver.h"

VDRFindServer::VDRFindServer( QObject *parent ) : QObject( parent )
{
    m_udpSocket = new QUdpSocket( this );

    m_socketEstablished = m_udpSocket->bind( 3024 );
    if ( !m_socketEstablished )
    {
        return;
    }

    connect( m_udpSocket, SIGNAL( readyRead() ),
             this,        SLOT( processPendingDatagrams() ) );
    connect( this,        SIGNAL( requestBroadcastDatagram() ),
             this,        SLOT( broadcastDatagram() ) );
}


VDRFindServer::~VDRFindServer()
{
}


QList<serverEntry> VDRFindServer::serverList()
{
    emit requestBroadcastDatagram();

    //Called from outside
    m_mutex.lock();

    m_waitingForServerFound.wait( &m_mutex );

    m_mutex.unlock();

    return m_serverList;
}


bool VDRFindServer::socketEstablished()
{
    QMutexLocker locker( &m_mutex );
    return m_socketEstablished;
}


void VDRFindServer::processPendingDatagrams()
{
    QHostAddress sender;

    while ( m_udpSocket->hasPendingDatagrams() )
    {
        QByteArray datagram;
        datagram.resize( m_udpSocket->pendingDatagramSize() );
        m_udpSocket->readDatagram( datagram.data(), datagram.size(), &sender );

        qDebug() << "VDRFindServer::Found server address: " << sender.toString() << datagram.data();

        serverEntry entry;
        entry.hostAddress = sender;
        entry.hostName = QString( datagram.data() );
        qDebug() << "VDRFindServer::Entry in List ip:" << entry.hostAddress << "  name: " << entry.hostName;
        bool found = false;

        for ( int i = 0; i < m_serverList.size(); ++i )
        {
            if ( m_serverList[i].hostAddress == sender )
                found = true;
        }

        if ( !found && datagram.data() != QByteArray( "VOMP" ) )
        {
            m_serverList.append( entry );
        }
    }
}


void VDRFindServer::broadcastDatagram()
{
    QByteArray datagram = "VOMP";
    m_udpSocket->writeDatagram( datagram.data(), datagram.size(), QHostAddress::Broadcast, 3024 );
    QTimer::singleShot( 500, this, SLOT( endWait() ) );
    qDebug() << "VDRFindServer::Broadcasted 'VOMP'";
}


void VDRFindServer::endWait()
{
    m_mutex.lock();
    m_waitingForServerFound.wakeAll();
    m_mutex.unlock();
}

